<template>
  <div>
    <el-dialog title="添加用户" :visible="isShow" @close="closeFn">
      <!-- 表单 -->
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码">
          <el-input v-model="form.password" />
        </el-form-item>
      </el-form>
      <span v-if="form.id">
        <!-- 上传头像 -->
        <span class="spa"><strong class="img">头像</strong></span> <uploadSomeImg ref="refImage" :count-image="1" />

      </span>

      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFn">取 消</el-button>
        <el-button type="primary" @click="addFn">确 定</el-button>

      </span>
    </el-dialog>

  </div>
</template>

<script>
import { register } from '@/api/user'
import { getOneRoles, editRolesApi } from '@/api/employees'
export default {
  props: {
    isShow: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        username: '', // 用户名
        email: '',
        password: '', // 密码
        image: '' // 图片
      }
    }
  },
  methods: {
    // 获取单条数据然后回填
    async backData(id) {
      const res = await getOneRoles(id)
      this.form = res.data
      this.$nextTick(() => {
        // 头像回显
        this.$refs.refImage.fileList = [{ url: res.data.image }]
        // console.log('this.$refs.refImage: ', this.$refs.refImage)
      })
    },
    // 确认按钮
    async addFn() {
      if (this.form.id) {
        // 编辑
        // 数组改造
        const newList = this.$refs.refImage.fileList.map((item) => {
          return item.url
        })
        // console.log(newList)
        this.form.image = newList[0]
        await editRolesApi(this.form)
        // console.log('this.form.image = newList[0]: ', this.form.image = newList[0])
      } else {
        await register(this.form)
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
      }

      // // 关闭弹框
      this.closeFn()
      // // 刷新页面
      this.$emit('roleList')
    },
    // 关闭模态框/清除数据
    closeFn() {
      this.$emit('update:isShow', false)
      this.form = {
        username: '', // 用户名
        email: '',
        password: '', // 密码
        image: '' // 图片
      }
    }
  }
}
</script>

<style>
.img{
  margin-left: 40px;
  margin-right: 10px;
}
.spa{
  margin-top: 20px;
}

</style>
